import React, { Component } from 'react';
import { Input, Transfer, Button, Table, Checkbox } from 'antd';
import difference from 'lodash/difference';
import { similarlibQuestionList } from '@/services/similarExt';

const { Search } = Input;

const TableTransfer = ({ leftColumns, rightColumns, ...restProps }) => (
  <Transfer {...restProps} showSelectAll={false} rowKey={record => record.id}>
    {({
      direction,
      filteredItems,
      onItemSelectAll,
      onItemSelect,
      selectedKeys: listSelectedKeys,
      disabled: listDisabled,
    }) => {
      const columns = direction === 'left' ? leftColumns : rightColumns;
      const onCheckAllChange = () => {
        console.log(filteredItems, restProps.rightData);
        let data = direction === 'left' ? filteredItems : restProps.rightData;
        let dataId = listSelectedKeys.length < data.length ? data.map(item => item.id) : null;
        let datafKeys = dataId ? difference(dataId, listSelectedKeys) : difference(listSelectedKeys, dataId);
        onItemSelectAll(datafKeys, dataId);
      };
      const disabled = direction === 'left'
        ? restProps.total === 0 ? true : false
        : filteredItems.length === 0 ? true : false;
      const checked = direction === 'left'
        ? restProps.total > 0 ? filteredItems.length === listSelectedKeys.length ? true : false : false
        : filteredItems.length > 0 ? restProps.rightData.length === listSelectedKeys.length ? true : false : false;
      const indeterminate = direction === 'left'
        ? restProps.total > 0 ? filteredItems.length !== listSelectedKeys.length && listSelectedKeys.length !== 0 ? true : false : false
        : filteredItems.length > 0 ? restProps.rightData.length !== listSelectedKeys.length && listSelectedKeys.length !== 0 ? true : false : false;
      const rowSelection = {
        columnTitle: () => {
          return <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} disabled={disabled} checked={checked}>全选</Checkbox>
        },
        columnWidth: 80,
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows.filter(item => !item.disabled).map(({ id }) => id);
          const diffKeys = selected
            ? difference(treeSelectedKeys, listSelectedKeys)
            : difference(listSelectedKeys, treeSelectedKeys);
          onItemSelectAll(diffKeys, selected);
        },
        onSelect({ id }, selected) {
          onItemSelect(id, selected);
        },
        selectedRowKeys: listSelectedKeys,
      };

      return (
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={direction === 'left' ? filteredItems : restProps.rightData}
          size="small"
          style={{ pointerEvents: listDisabled ? 'none' : null }}
          rowKey="id"
          pagination={{
            total: direction === 'left' ? restProps.total : filteredItems.length,
            onChange: direction === 'left' ? restProps.onPageChange : null,
            pageSize: 100,
          }}
          scroll={{ y: '60vh' }}
          loading={direction === 'left' ? restProps.loading : false}
        />
      );
    }}
  </Transfer>
);

class QuestionLib extends Component {
  state = {
    questions: null,
    loading: false,
    query: {
      size: 100,
      current: 1,
      question: '',
    },
    targetKeys: [],
    rightData: [],
    sourceSelectedKeys: [],
    targetSelectedKeys: [],
  };

  componentDidMount() {
    this.fetchData();
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  fetchData = async () => {
    const { query, loading } = this.state;
    let { questions } = this.state;
    this.setState({ loading: true });
    questions = await similarlibQuestionList(query);
    this.setState({ questions, loading: false });
  };

  handleSearch = value => {
    this.setState(
      {
        query: {
          ...this.state.query,
          current: 1,
          size: 100,
          question: value,
        },
      },
      this.fetchData
    );
  };

  onChange = (targetKeys, direction, moveKeys) => {
    let { rightData } = this.state;
    const { questions } = this.state;
    const { onChange } = this.props;
    if (direction === 'right') {
      rightData = questions.records.filter(item => targetKeys.indexOf(item.id) > -1);
    } else {
      rightData = rightData.filter(item => moveKeys.indexOf(item.id) == -1);
    }
    this.setState({ targetKeys, rightData }, () => {
      onChange(rightData);
    });
  };

  clearTargetKeys = () => {
    const { targetSelectedKeys } = this.state;
    let { targetKeys, rightData } = this.state;
    rightData = rightData.filter(item => targetSelectedKeys.indexOf(item.id) == -1);
    targetKeys = targetKeys.filter(item => targetSelectedKeys.indexOf(item) == -1);
    this.setState({ targetKeys, rightData });
  };

  selectAll = () => {
    const { questions, sourceSelectedKeys } = this.state;
    let { targetKeys, rightData } = this.state;
    const newTargetKeys = questions.records.filter(
      item => sourceSelectedKeys.indexOf(item.id) > -1
    );
    targetKeys = sourceSelectedKeys;
    rightData = newTargetKeys;
    this.setState({ targetKeys, rightData });
  };

  onPageChange = (current, size) => {
    this.setState(
      {
        query: {
          ...this.state.query,
          current,
          size,
        },
      },
      () => {
        this.fetchData();
      }
    );
  };

  triggerOnItemSelect = (sourceSelectedKeys, targetSelectedKeys) => {
    let {
      sourceSelectedKeys: newSourceSelectedKeys,
      targetSelectedKeys: newTargetSelectedKeys,
    } = this.state;
    newSourceSelectedKeys = sourceSelectedKeys;
    newTargetSelectedKeys = targetSelectedKeys;

    this.setState({
      sourceSelectedKeys,
      targetSelectedKeys,
    });
  };

  render() {
    const {
      questions,
      targetKeys,
      rightData,
      sourceSelectedKeys,
      targetSelectedKeys,
      loading,
    } = this.state;
    const leftTableColumns = [
      {
        dataIndex: 'question',
        title: '问题库',
      },
    ];
    const rightTableColumns = [
      {
        dataIndex: 'question',
        title: '待添加',
      },
    ];
    return (
      <div>
        <Search placeholder="输入问题关键词" onSearch={this.handleSearch} style={{ width: 350 }} />
        <TableTransfer
          dataSource={questions?.records}
          targetKeys={targetKeys}
          disabled={false}
          showSearch={false}
          onChange={this.onChange}
          leftColumns={leftTableColumns}
          rightColumns={rightTableColumns}
          style={{ marginTop: 20 }}
          listStyle={{
            width: 350,
          }}
          titles={[
            <Button
              size="small"
              onClick={this.selectAll}
              disabled={sourceSelectedKeys.length === 0}
            >
              批量添加
            </Button>,
            <Button
              size="small"
              onClick={this.clearTargetKeys}
              disabled={targetSelectedKeys.length === 0}
            >
              批量移除
            </Button>,
          ]}
          total={questions?.total}
          onPageChange={this.onPageChange}
          rightData={rightData}
          onSelectChange={this.triggerOnItemSelect}
          loading={loading}
        />
      </div>
    );
  }
}

export default QuestionLib;
